package com.duoduo.modules.controller;

import com.duoduo.common.entity.AuthUser;
import com.duoduo.common.fliter.StatelessRealm;
import com.duoduo.common.response.ErrorCode;
import com.duoduo.common.response.HttpStatus;
import com.duoduo.common.response.Result;
import com.duoduo.common.util.JWTUtil;
import com.duoduo.common.util.MD5Util;
import com.duoduo.common.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制类
 * @Author:
 * @CreateTime: 2023-10-18  09:32
 * @Description:
 * @Version: 1.0
 */
@RestController
@RequestMapping("auth/user")
@Api(tags = "用户控制")
public class AuthUserController extends BaseController{

    @PostMapping("login")
    @ApiOperation(value = "用户登陆", notes = "JSON格式数据,传输字段: mobile/password")
    public Result login(@RequestBody AuthUser authUser){
        // System.out.println("authUser = " + authUser);
        // 校验账户与密码, 可能抛出错误, 直接返回前端
        AuthUser user = verifyAccountAndPassword(authUser.getMobile(), authUser.getPassword());
        // 生成token并返回
        String tokenStr = null;
        try {
            tokenStr = makeTokenStrAndRecordTime(user);
        } catch (Exception e) {
            throw new RuntimeException("登录异常!");
        }
        Map<String, Object> data = new HashMap<>();
        data.put("token", tokenStr);
//        data.put("userId", user.getId());
        data.put("userName", user.getNickName());
//        data.put("role", JWTUtil.resolveClaim(tokenStr, "role"));
        return Result.builder()
                .code(ErrorCode.OK.value())
                .userTip("登录成功")
                .data(data)
                .build();
    }

    /**
     * 添加token信息
     *
     * @param user
     * @return
     */
    private String makeTokenStrAndRecordTime(AuthUser user) throws Exception {
//        // 查询角色信息
//        AuthUserRole authUserRole = userRoleService.queryByUserId(user.getId());
//        // 查询角色类型
//        AuthRole authRole = super.roleService.queryById(authUserRole.getARoleId());
//        // 查询部门
//        AuthDepart authDepart = departService.queryById(user.getADepartId());
        Map<String, String> payload = new HashMap<>();
        payload.put("userName", user.getNickName());
        payload.put("userId", user.getId() + "");
//        payload.put("role", authUserRole.getARoleId() == null ? null : authUserRole.getARoleId() + "");// 角色信息
        // 角色类型 1：系统角色 2：普通角色
//        payload.put("type", authRole.getAType() == 1 ? StatelessRealm.ADMIN_AUTHENTICATION : StatelessRealm.USER_AUTHENTICATION);// 用户类型
        // 记录登录时间
        //uUserService.updateUUserLoginTime(user.getUserName(), loginTime);
//        return JWTUtil.getToken(payload,20); 不添加时间默认720分钟
        return JWTUtil.getToken(payload);
    }

    /**
     * 校验用户的登录username与password</br>
     * 若校验通过，返回包含着用户信息的JavaBean对象</br>
     *
     * @param username
     * @param password
     * @return
     */
    private AuthUser verifyAccountAndPassword(String username, String password) {
        // 获取用户信息
        System.out.println("用户名" + username);
        AuthUser authUsers = userService.queryByMobile(username);

        if (StringUtils.isNull(authUsers)) {
            throw new RuntimeException(HttpStatus.NOT_REGISTER.value() + "#-#" + HttpStatus.NOT_REGISTER.getReasonPhrase());
//        } else if (!authUsers.getPassword().equals(MD5Util.getMD5PWD(password))) {  TODO 暂时不加密
        } else if (!authUsers.getPassword().equals(password)) {
            throw new RuntimeException(HttpStatus.USERNAME_OR_PASSWORD_ERROR.value() + "#-#" + HttpStatus.USERNAME_OR_PASSWORD_ERROR.getReasonPhrase());
        }
//        else if (authUsers.getABankStatus().equals("1")) {
//            throw new RuntimeException( "401#-#账户被锁定请联系管理员！" );
//        }
        return authUsers;
    }

    @PostMapping("register")
    @ApiOperation(value = "用户注册", notes = "JSON格式数据,传输字段: mobile/password")
    public Result register(String mobile, String password){
        if (StringUtils.isEmpty(mobile)){
            return Result.builder().code("A0410").userTip("手机号不能为空").build();
        }
        if (StringUtils.isEmpty(password)){
            return Result.builder().code("A0410").userTip("密码不能为空").build();
        }
        AuthUser authUser = new AuthUser();
        authUser.setMobile(mobile);
        authUser.setPassword(password);
        return userService.addUser(authUser);
    }

}
